package com.group.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.group.dao.CommentDao;
import com.group.dao.MediaDao;
import com.group.dao.UserDao;
import com.group.domain.Comment;
import com.group.domain.Media;
import com.group.domain.User;
import com.group.utils.HibernateUtil;

import jdk.internal.org.objectweb.asm.tree.analysis.Value;


/**
 * 管理员控制类
 * 
 * @author spj,cc
 * @version 1.0
 */
@Controller
@RequestMapping("/manager")
@SessionAttributes({ "manager" })
public class ManagerController {

	/** 用户信息数据表接口 **/
	UserDao userDao = new UserDao();
	/** 书音影信息数据表接口 **/
	MediaDao mediaDao = new MediaDao();
	/** 评论信息数据表接口 **/
	CommentDao commentDao = new CommentDao();

	/**
	 * 用户列表（根据页数和搜索参数生成）
	 * 
	 * @param map
	 * @param model
	 * @param page       页数
	 * @param searchName 查询的用户名
	 * @return
	 */
	@RequestMapping("/user")
	public String userList(ModelMap map, Model model, @RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "") String searchName) {
		long count = 0;
		List<User> userList = null;
		if ("".equals(searchName)) {
			count = userDao.count();
			userList = userDao.findUserListByPage(page, 8);
		} else {
			count = userDao.findUserListByName(searchName).size();
			userList = userDao.findUserLIstByName(searchName, page, 8);
		}
		map.addAttribute("page", page);
		map.addAttribute("searchName", searchName);
		model.addAttribute("pageCount", Math.ceil(count / 8.0));
		model.addAttribute("userList", userList);
		return "manager/user";
	}

	/**
	 * 管理员评论界面
	 * 
	 * @param map
	 * @param model
	 * @param page  页码
	 * @return
	 */
	@RequestMapping("/comment")
	public String commentList(ModelMap map, Model model, @RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "") String searchName) {
		long count = 0;
		List<Comment> commentList = null;
		if ("".equals(searchName)) {
			count = commentDao.count();
			commentList = commentDao.findCommentListByPage(page, 8);
		} else {
			count = commentDao.findCommentListByUser(userDao.findOneByName(searchName)).size();
			commentList = commentDao.findCommentListByPage(page, 8, userDao.findOneByName(searchName));
		}
		map.addAttribute("page", page);
		map.addAttribute("searchName", searchName);
		model.addAttribute("pageCount", Math.ceil(count / 8.0));
		model.addAttribute("commentList", commentList);
		return "manager/comment";
	}

	/**
	 * 管理员书影音界面
	 * 
	 * @param map
	 * @param model
	 * @param page
	 * @param title
	 * @return
	 */
	@RequestMapping("/media")
	public String mediaList(ModelMap map, Model model, @RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "") String title) {
		long count = 0;
		List<Media> mediaList = null;
		if ("".equals(title)) {
			count = mediaDao.count();
			mediaList = mediaDao.findMediaListByPage(page, 8);
		} else {
			count = mediaDao.findMediaListByTitle(title).size();
			mediaList = mediaDao.findMediaListByTitle(title, page, 8);
		}
		map.addAttribute("page", page);
		map.addAttribute("title", title);
		model.addAttribute("pageCount", Math.ceil(count / 8.0));
		model.addAttribute("mediaList", mediaList);
		return "manager/media";
	}
	
	/**
	 * 管理员首页
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/home")
	public String home(Model model) {
		// 获取用户信息
		//Manager manager = (Manager) model.asMap().get("manager");

		// 获取用户总数
		long userCount = userDao.count();

		// 获取书影音总数
		long mediaCount = mediaDao.count();

		// 获取评论总数
		long commentCount = commentDao.count();
		
		//获取图书总数
		long bookCount = mediaDao.countMeida("Book");
		
		//获取音乐总数
		long musicCount = mediaDao.countMeida("Music");
		
		//获取影视总数
		long movieCount = mediaDao.countMeida("Movie");
		
		// 将数据传入模型
		model.addAttribute("userCount", userCount);
		model.addAttribute("mediaCount", mediaCount);
		model.addAttribute("commentCount", commentCount);
		model.addAttribute("bookCount",bookCount);
		model.addAttribute("musicCount",musicCount);
		model.addAttribute("movieCount",movieCount);

		// 返回首页视图
		return "manager/home";
	}

	/**
	 * 添加用户
	 * 
	 * @param username 用户名
	 * @param password 密码
	 * @param email    邮箱
	 * @param role     用户权限（User/Admin）
	 * @param model
	 * @return 回到用户管理界面（刷新）
	 */
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	public String addUser(@RequestParam(value = "username", defaultValue = "") String username,
			@RequestParam(value = "password", defaultValue = "") String password,
			@RequestParam(value = "email", defaultValue = "") String email,
			@RequestParam(value = "phone", defaultValue = "") String phone,
			@RequestParam(value = "desc", defaultValue = "") String description,
			@RequestParam(value = "role", defaultValue = "false") String role, Model model) {
		// 1. 判断用户名是否重复
		if (userDao.findOneByName(username) != null) {
			// 重复用户名
			model.addAttribute("added", false);
			return "manager/user";
		}
		// 2. 根据信息新建用户
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setEmail(email);
		user.setPhone(phone);
		user.setDescription(description);
		user.setRegistrationDate(new Date());
		user.setRole(Boolean.parseBoolean(role));
		user.setIsDelete(false);
		// TODO 3. 执行保存语句
		userDao.saveUser(user);
		return "redirect:user";
	}

	/**
	 * 查询指定用户名的用户
	 * 
	 * @param searchName 用户名
	 * @param model
	 * @return LIKE用户名的用户列表
	 */
	@RequestMapping(value = "/searchUser", method = RequestMethod.POST)
	public String searchUser(@RequestParam(value = "searchName", defaultValue = "") String searchName, Model model,
			ModelMap map) {
		map.addAttribute("searchName", searchName);
		return "redirect:user";
	}

	/**
	 * 修改用户信息
	 * 
	 * @param id       用户id
	 * @param newName  新用户名
	 * @param newPsw   新密码
	 * @param newEmail 新邮箱
	 * @param newPhone 新手机号码
	 * @param newDesc  新签名
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/editUser", method = RequestMethod.POST)
	public String updateUser(@RequestParam(value = "userId") String id,
			@RequestParam(value = "editUsername") String newName, @RequestParam(value = "editPassword") String newPsw,
			@RequestParam(value = "editEmail") String newEmail, @RequestParam(value = "editPhone") String newPhone,
			@RequestParam(value = "editDesc") String newDesc, Model model) {
		User user = userDao.findOneById(Integer.parseInt(id));
		user.setUsername(newName);
		user.setPassword(newPsw);
		user.setEmail(newEmail);
		user.setPhone(newPhone);
		user.setDescription(newDesc);
		userDao.update(user);
		return "redirect:user";
	}

	/**
	 * 在此方法中添加一个媒体。
	 *
	 * @param type         媒体类型
	 * @param title        媒体标题
	 * @param author       作者
	 * @param release_date 发布日期
	 * @param description  描述信息
	 * @param imageUrl	图片链接
	 * @param model        Spring MVC中的Model对象
	 * @return 返回页面或重定向
	 */
	@RequestMapping(value = "/addMedia", method = RequestMethod.POST)
	public String addMedia(@RequestParam(value = "addItemType", defaultValue = "") String type,
			@RequestParam(value = "addBookTitle", defaultValue = "") String title,
			@RequestParam(value = "addBookAuthor", defaultValue = "") String author,
			@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @RequestParam(value = "addReleaseDate", defaultValue = "") Date release_date,
			@RequestParam(value = "addTag", defaultValue = "") String tag,
			@RequestParam(value = "addDescription", defaultValue = "") String description, 
			@RequestParam(value = "addLink", defaultValue = "") String imageUrl, Model model) {

		// 1. 判断media是否重复
		if (mediaDao.findBySimilarTitle(title) != null) {
			// 重复用户名
			model.addAttribute("added", false);
			return "manager/user";
		}
		// 2. 根据信息新建media
		Media media = new Media();
		media.setTitle(title);
		media.setType(type);
		media.setAuthor(author);
		media.setReleaseDate(release_date);
		media.setTag(tag);
		media.setDescription(description);
		media.setImageUrl(imageUrl);
		media.setIsDelete(false);
		// TODO 3. 执行保存语句
		mediaDao.saveMedia(media);
		return "redirect:media";
	}

	/**
	 * 根据标题搜索书影音。
	 *
	 * @param searchTitle 搜索标题
	 * @param model       Spring MVC中的Model对象
	 * @return 如果搜索标题为空则重定向到书影音管理界面，否则执行查询并返回到书影音管理页面
	 */
	@RequestMapping(value = "/searchMedia", method = RequestMethod.POST)
	public String searchMedia(@RequestParam(value = "title", defaultValue = "") String title, Model model,
			ModelMap map) {
		map.addAttribute("title", title);
		return "redirect:media";
	}

	/**
	 * 更新书影音信息。
	 *
	 * @param id             媒体ID
	 * @param newTitle       新的标题
	 * @param newAuthor      新的作者
	 * @param newDate        新的发行日期
	 * @param newTag         新的标签
	 * @param newDescription 新的描述
	 * @param model          Spring MVC中的Model对象
	 * @return 重定向到书影音管理界面
	 */
	@RequestMapping(value = "/editMedia", method = RequestMethod.POST)
	public String updateMedia(@RequestParam(value = "mediaId") String id,
			@RequestParam(value = "editBookTitle") String newTitle,
			@RequestParam(value = "editBookAuthor") String newAuthor,
			@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @RequestParam(value = "editReleaseDate") Date newDate,
			@RequestParam(value = "editBookTag") String newTag,
			@RequestParam(value = "editDescription") String newDescription,
			@RequestParam(value = "editLink")String Link ,Model model) {
		Media media = mediaDao.findOneById(Integer.parseInt(id));
		media.setTitle(newTitle);
		media.setAuthor(newAuthor);
		media.setReleaseDate(newDate);
		media.setTag(newTag);
		media.setDescription(newDescription);
		media.setImageUrl(Link);
		mediaDao.update(media);
		return "redirect:media";
	}
	/**
	 * 查询指定用户名的评论
	 * 
	 * @param searchName 用户名
	 * @param model
	 * @return LIKE用户名的评论列表
	 */
	@RequestMapping(value = "/searchComment", method = RequestMethod.POST)
	public String searchComment(@RequestParam(value = "searchName", defaultValue = "") String searchName, Model model,
			ModelMap map) {
		map.addAttribute("searchName", searchName);
		return "redirect:comment";
	}
	/**
	 * 删除用户
	 * 
	 * @param model
	 * @param id    用户id
	 * @return
	 */
	@RequestMapping(value = "deleteUser", method = RequestMethod.POST)
	public String deleteUser(Model model, @RequestParam(value = "userId") String id) {
		boolean flag = userDao.delete(Integer.parseInt(id));
		model.addAttribute("deleted", flag);
		return "redirect:user";
	}

	/**
	 * 删除评论
	 * 
	 * @param model
	 * @param id    用户id
	 */
	@RequestMapping(value = "deleteComment", method = RequestMethod.POST)
	public String deleteComment(Model model, @RequestParam(value = "commentId") String id) {
		boolean flag = commentDao.delete(Integer.parseInt(id));
		model.addAttribute("deleted", flag);
		return "redirect:comment";
	}
	

	/**
	 * 删除media
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "deleteMedia",method = RequestMethod.POST)
	public String deleteMedia(Model model,@RequestParam(value = "mediaId") String id) {
		boolean flag = mediaDao.delete(Integer.parseInt(id));
		model.addAttribute("delete",flag);
		return "redirect:media";
	}

}